const Http = {};
['get','post'].forEach(method=>{
	Http[method] = (url,data,opt)=>{
		return _fetch({url,method,data,opt});
	}
});
function _fetch({
	url,
	method="GET",
	data={},
	opt
}) {
	let opts = {
	  method
	}
	let params = (obj)=>{
		let pars = [];
		let keys = Object.keys(obj);
		for(let i=0;i<keys.length;i++){
			pars.push(keys[i]+'='+obj[keys[i]]);
		}
		return pars.join('&');
	}
	let user = localStorage.getItem('e_book_user');
	if (user) {
		user = JSON.parse(user);
		data.token=user.token;
	}else{
		console.log('请登录')
	}
	if(method==="post"){
		opts.headers = {
		    'Content-Type': 'application/x-www-form-urlencoded'
		}
		opts.body=params(data);
	}
	if(method==="get"){
		url+=((/\?$|\?.+?&$/i.test(url))?'':/\?.+?[^&]$/i.test(url)?'&':'?')+params(data);
	}
	if (opt) {
		opts = {...opts,...opt};
	}
	return fetch(url, opts)
	.then(res=>res.json())
}

export default Http;